<?php

namespace app\model;

use think\facade\Db;
use think\Model;

class OrdersModel extends Model {

    protected $table ="orders";

    protected $pk = 'order_id';

    private $cacheKey="order:id:";

    private $cacheTime=5184000;


    /*
     * 获取total
     * */
    public function getTotal($where=[]){
        return  Db::name('orders')
            ->alias("o")
            ->field("o.order_id")
            ->leftJoin('shops s','o.shop_id = s.shop_id')
            ->leftJoin('order_items it','o.order_id = it.order_id')
            ->where($where)->count();
    }


    /*
     * 获取list
     * */
    public function getList($where=[],$page = null,$limit = null,$orderField = null,$orderType = "ASC"){

        $obj =   Db::name('orders')
            ->alias("o")
            ->field("DISTINCT(o.order_id)")
            ->where($where)
            ->leftJoin('shops s','o.shop_id = s.shop_id')
            ->leftJoin('order_items it','o.order_id = it.order_id');

        if(!empty($page) && !empty($limit)){
            $obj = $obj->page($page, $limit);
        }

        if(!empty($orderField) && !empty($orderType)){
            $obj = $obj->order($orderField, $orderType);
        }

        $list = $obj->select();

        if($list){
            $return = [];
            foreach($list as $item){
                $return[] = $this->getInfo($item['order_id']);
            }
            return $return;
        }
        return [];
    }



    /*
   * 获取订单状态详情
   * */
    public function getInfo($order_id){

        $cacheKey = $this->cacheKey.$order_id;
        $redisModel = new RedisModel();
        $info = $redisModel->get($cacheKey);
        if($info){
            $orderInfo =  json_decode($info,true);
        }else{
            $orderInfo = Db::name('orders')->find($order_id);
            if(empty($orderInfo)) return [];
            $orderInfo["format_total_amount"] = round(  $orderInfo["total_amount"] / 100,2);
            $orderInfo["format_total_shipping_fee"] = round(  $orderInfo["total_shipping_fee"] / 100,2);
            $orderInfo["format_total_pay_amount"] = round(  $orderInfo["total_pay_amount"] / 100,2);
            $orderInfo["format_total_discount_amount"] = round(  $orderInfo["total_discount_amount"] / 100,2);
            $redisModel->set($cacheKey,json_encode($orderInfo,256),$this->cacheTime);
        }

        if($orderInfo){
            //是否可以极速退款
            $orderInfo['is_can_fast'] = $this->isOrderCanFastRefund($order_id) > 0 ? 1 : 0;
            //处理地址信息
            $orderInfo["sender_info"] = !empty($orderInfo["sender_info"]) ? json_decode($orderInfo["sender_info"],true) : "";
            $orderInfo["receiver_info"] = !empty($orderInfo["receiver_info"]) ? json_decode($orderInfo["receiver_info"],true) : "";
            $orderInfo["return_info"] = !empty($orderInfo["return_info"]) ? json_decode($orderInfo["return_info"],true) : "";
            //实时获取最新订单状态
            $orderInfo["order_status"] = $this->getOrderStatus($order_id);
            //获取支付数据
            if(!in_array($orderInfo["order_status"],[0])){
                $wxPayInfo = $this->getOrderPayInfo($order_id);
                $wxPayInfo["wx_pay_info"] = !empty($wxPayInfo["wx_pay_info"]) ? json_decode($wxPayInfo["wx_pay_info"],true) : "";
                $orderInfo["wx_transaction_id"] = $wxPayInfo["wx_transaction_id"];
                $orderInfo["pay_status"] = $wxPayInfo["pay_status"];
                $orderInfo["pay_time"] = $wxPayInfo["pay_time"];
                $orderInfo["wx_pay_info"] = $wxPayInfo["wx_pay_info"];
            }

            //获取状态文案
            $orderInfo["status_info"]  = (new BaseOrderStatus())->getInfo( $orderInfo["order_status"]);
            //实时获取订单售后状态
            $orderInfo["aftersale_status"] = $this->getOrderAftersalesStatus($order_id);
            if($orderInfo['order_status'] == -1  && $orderInfo["aftersale_status"] == 3){
                $orderInfo["status_info"]["order_status_name"] = "交易取消/退款完成";
                $orderInfo["status_info"]["order_status_desc"] = "交易取消/退款完成";
            }

            //获取售后状态文案
            $orderInfo["aftersale_status_info"]  = (new BaseOrderAftersalesStatus())->getInfo( $orderInfo["aftersale_status"]);
            //判断售后状态文案
            $orderInfo["aftersales_info"] =[];
            if($orderInfo["aftersale_status"]){
                $orderInfo["aftersales_info"] = (new OrderAftersalesModel())->isRunOrderAftersales($order_id);
                if(empty($orderInfo["aftersales_info"])){
                    $orderInfo["aftersales_info"] = (new OrderAftersalesModel())->isRunOrderAftersales($orderInfo['p_order_id']);
                }
            }

            //获取店铺信息
            $orderInfo["shop_info"] = (new ShopsModel())->getInfo($orderInfo["shop_id"]);

            //订单商品信息
            $orderInfo["itemsList"] = (new OrderItemsModel())->getOrderItemsList($order_id);

            //物流信息
            $orderInfo["logisticsInfo"] = (new OrderLogisticsModel())->getOrderLogisticsInfo($order_id);

            $orderInfo["order_have_send_spec_ids"] =[];
            if(!empty($orderInfo["logisticsInfo"])){
                $ids=[];
                foreach($orderInfo["logisticsInfo"] as $item){
                    $ids = array_merge($ids,$item["spec_ids"]);
                }
                $orderInfo["order_have_send_spec_ids"] = array_unique($ids);
            }

            //用户信息
            $orderInfo['userInfo'] = (new UserModel())->getUserInfoByUid($orderInfo["uid"]);

            $orderInfo['remain_time'] =   strtotime($orderInfo["created_at"]) + 30 * 60 - time();


            return $orderInfo;
        }

        return [];
    }


    /*
     * 根据联合订单号获取子订单
     * */
    public function getOrderByPOrderId($p_order_id){
        if(!isUnionOrderId($p_order_id)){
            return [$p_order_id];
        }
        $where[] = ['p_order_id','=',$p_order_id];
        $list =   Db::name('orders')
            ->alias("o")
            ->field("o.order_id")
            ->where($where)
            ->select();
        return array_column($list->toArray(),"order_id");
    }



    /*
     * 根据订单号获取联合订单
     * */
    public function getPOrderIdByOrderId($order_id){
        if(isUnionOrderId($order_id)){
            return $order_id;
        }
        $where[] = ['order_id','=',$order_id];
        return Db::name('orders')
            ->where($where)
            ->value("p_order_id");
    }



    /*
     * 获取今日交易数
     * */
    public function getTradeNum($shopIds){
        if(empty($shopIds)) return [];
        $date = date('Y-m-d');
        $where[] = ['o.shop_id','IN',$shopIds];
        $where[] = ['pay_status','=',1];
        $where[] = ['aftersale_status','=',0];
        $where[] = ['o.is_delete','=',0];
        $where[] =['pay_time','between',[$date." 00:00:00",$date." 23:59:59"]];

        return $this->getTotal($where);
    }

    /*
     * 获取今日交易总金额
     * */
    public function getTradeTotalAmount($shopIds){
        if(empty($shopIds)) return [];
        $date = date('Y-m-d');
        $where[] = ['shop_id','IN',$shopIds];
        $where[] = ['pay_status','=',1];
        $where[] = ['aftersale_status','=',0];
        $where[] =['pay_time','between',[$date." 00:00:00",$date." 23:59:59"]];

        return Db::name('orders')
            ->where($where)
            ->sum("total_amount");
    }

    /*
     * 获取未发货数量
     * */
    public function getUnSendNum($shopIds){
        if(empty($shopIds)) return [];
        $where[] = ['o.shop_id','IN',$shopIds];
        $where[] = ['order_status','=',1];
        $where[] = ['pay_status','=',1];
        $where[] = ['aftersale_status','=',0];
        $where[] = ['o.is_delete','=',0];

        return $this->getTotal($where);
    }


    /*
     * 未处理售后单
     *
     * */

    public function getUnHandelAftersalesNum(array $shopIds){
        if(empty($shopIds)) return [];
        $where[] = ['o.shop_id','IN',$shopIds];
        $where[] = ['pay_status','=',1];
        $where[] = ['aftersale_status','IN',[1,2]];
        $where[] = ['o.is_delete','=',0];

        return $this->getTotal($where);
    }


    /*
   * 生成订单
   * */
    public function bacthAdd($list){
       return Db::name('orders')->insertAll($list);
    }


    /*
     * 判断是不是用户的订单
     * */
    public function isUserOrder($uid,$order_id){
        $where['uid'] = $uid;
        $where['o.order_id|o.p_order_id'] = $order_id;
        $where['o.is_delete'] = 0;
        return $this->getTotal($where);
    }


    /*
  * 获取订单总金额total_amount
  * */
    public function getOrderTotalAmount($order_id){
        $where['order_id|p_order_id'] = $order_id;
        return Db::name('orders')->where($where)->sum("total_pay_amount");
    }

    /*
  * 获取联合订单总金额total_amount
  * */
    public function getUnionOrderTotalAmount($order_id){
        $where['order_id|p_order_id'] = $order_id;
        return Db::name('orders')->where($where)->sum("total_pay_amount");
    }


    /*
     * 订单是否允许急速退款
     * */
    public function isOrderCanFastRefund($order_id){
        $where['o.order_id'] = $order_id;
        $where['o.is_delete'] = 0;
        $where['o.pay_status'] = 1;
        $where['o.order_status'] = 1;
        return $this->getTotal($where);
    }


    /*
    * 获取订单状态
    * */
    public function getOrderStatus($order_id){
        if(empty($order_id) ){
            return false;
        }
        $where=[];
        $where[] = ["order_id","=",$order_id];
        return Db::name('orders')->where($where)->value("order_status");
    }


    /*
  * 获取订单状态
  * */
    public function getOrderPayInfo($order_id){
        if(empty($order_id) ){
            return false;
        }
        $where=[];
        $where[] = ["order_id","=",$order_id];
        return Db::name('orders')->field("pay_status,pay_time,wx_transaction_id,wx_pay_info,wx_cash_fee")->where($where)->find();
    }


    /*
   * 获取售后状态
   * */
    private function getOrderAftersalesStatus($order_id){
        if(empty($order_id) ){
            return false;
        }
        $where=[];
        $where[] = ["order_id","=",$order_id];
        return Db::name('orders')->where($where)->value("aftersale_status");
    }


    /*
     * 获取订单支付状态
     * */
    public function getOrderPayStatus($order_id){
        if(empty($order_id) ){
            return false;
        }
        $where=[];
        $where[] = ["order_id","=",$order_id];
        return Db::name('orders')->where($where)->value("pay_status");
    }



    /*
     * 检查联合订单中是否存在已支付的子订单
     *
     * */
    public function checkUnionOrderIsHavePay($p_order_id){
        $where=[];
        $where[] = ["o.p_order_id","=",$p_order_id];
        $where[] = ["o.pay_status","=",1];
        $where[] = ["o.is_delete","=",0];
        return $this->getTotal($where);
    }


    /*
 * 更新订单状态
 * */
    public function updateOrderStatus($order_id,$order_status = null){
        if(empty($order_id) || is_null($order_status) ){
            return false;
        }

        $where=[];
        $where[] = ["p_order_id|order_id","=",$order_id];
        return $this->updateAll($where,["order_status"=>$order_status]);
    }


    /*
* 更新订单状态
* */
    public function updateOrderAutoSignTime($order_id,$auto_sign_time = null){
        if(empty($order_id) || is_null($auto_sign_time) ){
            return false;
        }

        $where=[];
        $where[] = ["p_order_id|order_id","=",$order_id];
        return $this->updateAll($where,["auto_sign_time"=>$auto_sign_time]);
    }


    /*
    * 更新订单售后状态
    * */
    public function updateOrderAftersaleStatus($order_id,$aftersale_status = null){
        if(empty($order_id) || is_null($aftersale_status) ){
            return false;
        }
        $where=[];
        $where[] = ["p_order_id|order_id","=",$order_id];
        $save =[];
        $save['aftersale_status'] = $aftersale_status;
        return $this->updateAll($where,$save);
    }



    /*
     * 批量处理超时订单
     * */
    public function batchHandleTimeOutOrder(){
        $where=[];
        $where[] = ["order_status","=",0];
        $where[] = ["is_delete","=",0];
        $where[] = ["created_at","<", date("Y-m-d H:i:s",time() - 30 * 60)];
        return $this->updateAll($where,["order_status"=>-1]);
    }



    /*
     * 检查订单是否修改过地址
     * */
    public function isOrderHaveEditAddress($order_id){
        $where['o.order_id|p_order_id'] = $order_id;
        $where['o.is_delete'] = 0;
        $where['o.is_edit_address'] = 1;
        return $this->getTotal($where);
    }

    /*
      * 修改地址
      * */

    public function editOrderAddress($order_id,$receiver_info){
        $where['order_id|p_order_id'] = $order_id;
        $where['is_delete'] = 0;

        return $this->updateAll($where,[
            "receiver_info"=>json_encode($receiver_info,256)
        ]);
    }
    /*
     * 修改备注
     * */

    public function editOrderRemark($order_id,$remark){
        $where['order_id|p_order_id'] = $order_id;
        $where['is_delete'] = 0;

        return $this->updateAll($where,[
            "remark"=>$remark
        ]);
    }

    /*
     * 支付成功
     * */
    public function markAsPaid($order_id,$message){
        if(isUnionOrderId($order_id)){
            $where['p_order_id'] = $order_id;
        }else{
            $where['order_id'] = $order_id;
        }
        $where['order_status'] = 0;
        return $this->updateAll($where,[
            "pay_status"=>1,
            "order_status"=>1,
            "wx_transaction_id"=>$message["transaction_id"],
            "wx_cash_fee"=>$message["cash_fee"],
            "wx_pay_info"=>json_encode($message,256),
            "pay_time"=>date("Y-m-d H:i:s",time())
        ]);
    }




    /*
  * 支付失败
  * */
    public function markAsFailed($order_id,$message){
        if(isUnionOrderId($order_id)){
            $where['p_order_id'] = $order_id;
        }else{
            $where['order_id'] = $order_id;
        }
        $where['order_status'] = 0;
        return $this->updateAll($where,[
            "pay_status"=>-1,
            "wx_pay_info"=>json_encode($message,256),
            "pay_time"=>date("Y-m-d H:i:s",time())
        ]);
    }


    /*
     * 确认发货
     * */
    public function deliver($order_id, $senderInfo,$returnInfo,$is_all_send){
        $where['order_id'] = $order_id;
        $data =[];
        $data["order_status"] = 3;
        $data["is_all_send"] = $is_all_send;
        $data["sender_info"] = json_encode($senderInfo,256);
        if(!empty($returnInfo)){
            $data['return_info'] = json_encode($returnInfo,256);
        }
        $data["updated_at"] = date("Y-m-d H:i:s");
        return $this->updateAll($where,$data);
    }

    /*
     * 修改发货人地址
     * */
    public function editSender($order_id, $senderInfo){
        $where['order_id'] = $order_id;
        return $this->updateAll($where,[
            "sender_info"=>json_encode($senderInfo,256)
        ]);
    }

    /*
     * 修改退货地址
     * */
    public function editReturn($order_id, $returnInfo){
        $where['order_id'] = $order_id;
        return $this->updateAll($where,[
            "return_info"=>json_encode($returnInfo,256)
        ]);
    }



    public function batchUpdate($datas)
    {
        return $this->saveAll($datas);
    }

    /*
     * 更新条件更新订单
     * */
    public function updateAll($where,$data){
       return Db::name('orders')->where($where)->update($data);
    }




    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }
}